package com.yzh.wanandroid.component.fragment

import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.yzh.wanandroid.R
import com.yzh.wanandroid.adapter.WxArticListAdapter
import com.yzh.wanandroid.base.MvvmFragment
import com.yzh.wanandroid.databinding.FragmentWxArticleBinding
import com.yzh.wanandroid.network.retrofit.responsebean.TitleData
import com.yzh.wanandroid.vm.WxArticleFragmentVm
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class WxArticleFragment(var wxArticleTitle: TitleData) : MvvmFragment<FragmentWxArticleBinding,
        WxArticleFragmentVm>() {

    private var TAG = "WxArticleFragment"

    private val mAdapter by lazy { WxArticListAdapter() }

    override fun initViewModel(): WxArticleFragmentVm = createViewModel()

    override fun getLayoutId() = R.layout.fragment_wx_article

    override fun initView(view: View) {
        initRecyclerView()
        initSwipeRefresh()
    }

    override fun initData() {
        initBinding()
    }

    override fun onLazyLoad() {
        super.onLazyLoad()
        loadWxArticleData()
    }


    private fun initBinding() {
        mBinding.run {
            netWorkData = mViewModel.netWorkData
            adapter = mAdapter
            refreshData = mAdapter.refreshData
            fragment = this@WxArticleFragment
        }
    }

    private fun initRecyclerView() {
        mBinding.run {
            var linearLayoutManager = LinearLayoutManager(requireActivity())
            linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
            wxArticleList.layoutManager = linearLayoutManager
        }
    }

    /**
     * 初始化 SwipeRefreshLayout
     */
    private fun initSwipeRefresh() {
        mBinding.run {
            wxArticleSwipeRefresh.setColorSchemeResources(R.color.color_main)
            wxArticleSwipeRefresh.setOnRefreshListener { initData() }
        }
    }

    private fun loadWxArticleData() {
        lifecycleScope.launch {
            try {
                mViewModel.getData(wxArticleTitle.id).collectLatest {
                    mAdapter.submitData(it)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    fun onReloadClick() {

    }
}